package com.sangananitsolution.gogoproject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.sangananitsolution.fragments.MainBackgroundFragment;
import com.sangananitsolution.fragments.MyFavouirte;
import com.sangananitsolution.fragments.MyGarbageSale_CreateNew;
import com.sangananitsolution.fragments.MySearch;
import com.sangananitsolution.fragments.MygarbageSale;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class PhotoHandlingClass extends Activity {
	private static final int REQUEST_CODE = 1;
	int i = 0;
	private Bitmap bitmap;
	Button camera;
	// Activity request codes
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;

	// directory name to store captured images and videos
	private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

	private Uri fileUri; // file url to store image/video

	private ImageView imageView, imageView1, imageView2, imageView3,
			imageView4, imageView5, imageView6, imageView7, imageView8,
			imageView9, imageback;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.uploadimage);

		imageView = (ImageView) findViewById(R.id.imageupload1);
		imageView1 = (ImageView) findViewById(R.id.imageupload2);
		imageView2 = (ImageView) findViewById(R.id.imageupload3);
		imageView3 = (ImageView) findViewById(R.id.imageupload4);
		imageView4 = (ImageView) findViewById(R.id.imageupload5);
		imageView5 = (ImageView) findViewById(R.id.imageupload6);
		imageView6 = (ImageView) findViewById(R.id.imageupload7);
		imageView7 = (ImageView) findViewById(R.id.imageupload8);
		imageView8 = (ImageView) findViewById(R.id.imageupload9);
		imageView9 = (ImageView) findViewById(R.id.imageupload10);
		imageback = (ImageView) findViewById(R.id.imagebackarroe);

		camera = (Button) findViewById(R.id.btncamera);

		// Checking camera availability
		if (!isDeviceSupportCamera()) {
			Toast.makeText(getApplicationContext(),
					"Sorry! Your device doesn't support camera",
					Toast.LENGTH_LONG).show();
			// will close the app if the device does't have camera
			finish();
		}

		imageback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				MyGarbageSale_CreateNew createNew = new MyGarbageSale_CreateNew();

				/*Toast.makeText(getApplicationContext(),
						"Sorry! Your device doesn't support camera",
						Toast.LENGTH_LONG).show();*/
				
				
	/*			android.app.FragmentManager fragmentManager = getFragmentManager();
				android.app.FragmentTransaction fragmentTransaction = fragmentManager
						.beginTransaction();

				fragmentTransaction
						.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

				fragmentTransaction.addToBackStack(null);
				fragmentTransaction.replace(R.id.mainfragmentlayout,
						new  MainBackgroundFragment());
				fragmentTransaction.commit();
*/
				
				
				
				/* Intent intent = new Intent();
			        intent.setClass(PhotoHandlingClass.this, MyGarbageSale_CreateNew.class);
			        intent.putExtra("Bitmap", bitmap);
			        startActivity(intent)*/
				startActivity(new Intent(getApplicationContext(), MainBackgroundFragment.class));	
				
				
			}
		});
	}

	/**
	 * Checking device has camera hardware or not
	 * */
	private boolean isDeviceSupportCamera() {
		if (getApplicationContext().getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA)) {
			// this device has a camera
			return true;
		} else {
			// no camera on this device
			return false;
		}
	}

	public void takephotofromCamera(View view) {

		Intent intentcamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

		intentcamera.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

		// start the image capture Intent
		startActivityForResult(intentcamera, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

		// dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);

	}

	public void picfromgallery(View view) {

		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		startActivityForResult(intent, REQUEST_CODE);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CODE: {
			if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
				try {
					// We need to recyle unused bitmaps
					/*
					 * if (bitmap != null) { bitmap.recycle(); }
					 */

					if (bitmap != null && !bitmap.isRecycled()) {
						// bitmap.recycle();
						bitmap = null;
					}
					InputStream stream = getContentResolver().openInputStream(
							data.getData());
					bitmap = BitmapFactory.decodeStream(stream);

					Bitmap croppedBmp = Bitmap.createBitmap(bitmap, 0, 0,
							bitmap.getWidth(), bitmap.getHeight() - 1);
					stream.close();
					switch (i) {
					case 0:
						imageView.setImageBitmap(croppedBmp);
						i++;
						break;
					case 1:
						imageView1.setImageBitmap(croppedBmp);
						i++;
						break;
					case 2:
						imageView2.setImageBitmap(croppedBmp);
						i++;
						break;
					case 3:
						imageView3.setImageBitmap(croppedBmp);
						i++;
						break;
					case 4:
						imageView4.setImageBitmap(croppedBmp);
						i++;
						break;
					case 5:
						imageView5.setImageBitmap(croppedBmp);
						i++;
						break;
					case 6:
						imageView6.setImageBitmap(croppedBmp);
						i++;
						break;
					case 7:
						imageView7.setImageBitmap(croppedBmp);
						i++;
						break;
					case 8:
						imageView8.setImageBitmap(croppedBmp);
						i++;
						break;
					case 9:
						imageView9.setImageBitmap(croppedBmp);
						i++;
						break;

					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			super.onActivityResult(requestCode, resultCode, data);
		}
			break;

		case CAMERA_CAPTURE_IMAGE_REQUEST_CODE: {

			if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
				if (resultCode == RESULT_OK) {
					// successfully captured the image
					// display it in image view
					previewCapturedImage();
					// setPic();
				} else if (resultCode == RESULT_CANCELED) {
					// user cancelled Image capture
					Toast.makeText(getApplicationContext(),
							"User cancelled image capture", Toast.LENGTH_SHORT)
							.show();
				} else {
					// failed to capture image
					Toast.makeText(getApplicationContext(),
							"Sorry! Failed to capture image",
							Toast.LENGTH_SHORT).show();
				}
			}

			break;
		}

		default:
			break;
		}

	}

	/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {

			// hide video preview

			// imageView.setVisibility(View.VISIBLE);

			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 5;

			bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
			Bitmap croppedBmp = Bitmap.createBitmap(bitmap, 0, 0,
					bitmap.getWidth(), bitmap.getHeight() - 1);

			// imageView.setImageBitmap(bitmap);

			switch (i) {
			case 0:
				imageView.setImageBitmap(croppedBmp);
				imageView.setVisibility(View.VISIBLE);
				i++;
				break;
			case 1:
				imageView1.setImageBitmap(croppedBmp);
				imageView1.setVisibility(View.VISIBLE);
				i++;
				break;
			case 2:
				imageView2.setImageBitmap(croppedBmp);
				imageView2.setVisibility(View.VISIBLE);
				i++;
				break;
			case 3:
				imageView3.setImageBitmap(croppedBmp);
				imageView3.setVisibility(View.VISIBLE);
				i++;
				break;
			case 4:
				imageView4.setImageBitmap(croppedBmp);
				imageView4.setVisibility(View.VISIBLE);
				i++;
				break;
			case 5:
				imageView5.setImageBitmap(croppedBmp);
				imageView5.setVisibility(View.VISIBLE);
				i++;
				break;
			case 6:
				imageView6.setImageBitmap(croppedBmp);
				imageView6.setVisibility(View.VISIBLE);
				i++;
				break;
			case 7:
				imageView7.setImageBitmap(croppedBmp);
				imageView7.setVisibility(View.VISIBLE);
				i++;
				break;
			case 8:
				imageView8.setImageBitmap(croppedBmp);
				imageView8.setVisibility(View.VISIBLE);
				i++;
				break;
			case 9:
				imageView9.setImageBitmap(bitmap);
				imageView9.setVisibility(View.VISIBLE);
				i++;
				break;

			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	/*
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
		} else {
			return null;
		}

		return mediaFile;
	}

	/*
	 * Here we store the file url as it will be null after returning from camera
	 * app
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// save file url in bundle as it will be null on scren orientation
		// changes
		outState.putParcelable("file_uri", fileUri);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		// get the file url
		fileUri = savedInstanceState.getParcelable("file_uri");
	}

}
